<template>
    <div>
      <el-breadcrumb separator-class="el-icon-arrow-right">
        <el-breadcrumb-item>资讯管理</el-breadcrumb-item>
        <el-breadcrumb-item>资讯列表</el-breadcrumb-item>
      </el-breadcrumb>
      <el-card>
        <el-button @click="showAddNews">添加校园资讯</el-button>
        <el-table
          :header-cell-style="centerStyle"
          :cell-style="centerStyle"
          :data="newsList"
          stripe
          style="width: 100%">
          <el-table-column
            type="index"
            label="序号">
          </el-table-column>
          <el-table-column
            prop="title"
            label="标题"
            :show-overflow-tooltip="true">
          </el-table-column>
          <el-table-column
            prop="date"
            label="发布时间"
            width="100">
          </el-table-column>
          <el-table-column
            prop="content"
            label="内容"
            :show-overflow-tooltip="true">
          </el-table-column>
          <el-table-column
            prop="imageurl"
            label="图片"
            :show-overflow-tooltip="true">
            <template slot-scope="scope">
              <span v-if="scope.row.imageurl == null">无</span>
              <span v-else>{{scope.row.imageurl}}</span>
            </template>
          </el-table-column>
          <el-table-column
            label="操作">
            <template slot-scope="scope">
              <el-button @click="showNews(scope.row.id)">查看</el-button>
              <el-button @click="deleteNews(scope.row.id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="queryInfo.pagenum"
          :page-sizes="[1, 3, 5, 10]"
          :page-size="queryInfo.pagesize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total">
        </el-pagination>
        <el-dialog
          :visible.sync="showDialogVisible"
          width="40%">
              <div class="news_info">
                <div class="title">{{newsInfo.title}}</div>
                <div class="date">{{newsInfo.date}}</div>
                <div class="content">{{newsInfo.content}}</div>
                <div class="img">
                  <img :src="newsInfo.imageurl" width="70%" />
                </div>
              </div>
        </el-dialog>
        <el-dialog
          :visible.sync="showAddDialogVisible"
          width="50%" title="添加资讯" @close='AddDialogColsed'>
          <el-form :model="addNewsForm" :rules="addNewRules" ref="addNewsFormRef" label-width="100px">
            <el-form-item label="标题" prop="title">
              <el-input v-model="addNewsForm.title"></el-input>
            </el-form-item>
            <el-form-item label="内容"  prop="content">
              <el-input v-model="addNewsForm.content" type="textarea" :autosize="{ minRows: 10 }"></el-input>
            </el-form-item>
            <el-upload
            class="upload-demo"
            action="http://localhost:8080/imageUpload"
            ref='upload'
            :on-preview="handlePreview"
            :on-remove="handleRemove"
            :on-success="handleSuccess"
            list-type="picture"
            :limit= '1'
            :on-exceed="limit" >
            <el-button class="uploadBtn">上传图片</el-button>
          </el-upload>
          </el-form>
          <span slot="footer" class="dialog-footer">
            <el-button type="primary" @click="SubmitNews">发 布</el-button>
          </span>
        </el-dialog>
        <el-dialog
        :visible.sync="showImgDialogVisible"
        width="35%"
        title="图片预览">
          <img :src="addNewsForm.imageurl" width="100%">
        </el-dialog>
      </el-card>
    </div>
</template>

<script>
export default {
  data () {
    return {
      queryInfo: {
        searchwords: '',
        pagesize: 10,
        pagenum: 1
      },
      newsList: [],
      total: 0,
      showDialogVisible: false,
      newsInfo: {
        contet: '',
        date: '',
        title: '',
        imageurl: ''
      },
      showAddDialogVisible: false,
      showImgDialogVisible: false,
      addNewsForm: {
        title: '',
        content: '',
        imageurl: ''
      },
      addNewRules: {
        title: [
          { required: true, message: '请输入标题', trigger: 'blur' }
        ],
        content: [
          { required: true, message: '请输入内容', trigger: 'blur' }
        ]
      }
    }
  },
  created () {
    this.getNewsList()
  },
  methods: {
    // 获取新闻列表
    async getNewsList () {
      const res = await this.$http.get('news/getAllNewsByPage', {
        params: {
          pageNum: this.queryInfo.pagenum,
          pageSize: this.queryInfo.pagesize
        }
      })
      if (res.status !== 200) {
        this.$message.error('获取校园资讯列表失败')
      } else {
        this.newsList = res.data.list
        this.total = res.data.total
      }
    },
    // 表格内容居中样式
    centerStyle () {
      return 'text-align: center'
    },
    handleSizeChange (newSize) {
      this.queryInfo.pagesize = newSize
      this.getNewsList()
    },
    handleCurrentChange (newPage) {
      this.queryInfo.pagenum = newPage
      this.getNewsList()
    },
    // 查看资讯信息
    async showNews (id) {
      this.showDialogVisible = true
      const res = await this.$http.get('news/selectNewsById?id=' + id)
      this.newsInfo = res.data[0]
    },
    // 删除资讯
    async deleteNews (id) {
      const name = window.sessionStorage.getItem('name')
      if (name !== null) {
        this.$confirm('此操作将永久删除该资讯, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(async () => {
          const res = await this.$http.post('news/deleteNewsById?id=' + id)
          if (res.data === 'success') {
            this.$message.success('删除成功')
            this.getNewsList()
          }
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
      } else {
        this.$confirm('您还没有登录，请先登录', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.$router.push('/login')
        }).catch(() => {
          return false
        })
      }
    },
    // 打开添加资讯对话框
    showAddNews () {
      const name = window.sessionStorage.getItem('name')
      if (name !== null) {
        this.showAddDialogVisible = true
      } else {
        this.$confirm('您还没有登录，请先登录', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.$router.push('/login')
        }).catch(() => {
          return false
        })
      }
    },
    // 关闭添加资讯对话框
    AddDialogColsed () {
      this.$refs.addNewsFormRef.resetFields()
      this.$refs.upload.clearFiles()
      this.addNewsForm.imageurl = ''
    },
    // 图片上传成功函数
    handleSuccess (response) {
      this.addNewsForm.imageurl = response
    },
    // 查看上传的图片
    handlePreview (file) {
      this.showImgDialogVisible = true
    },
    // 移除上传的图片
    handleRemove () {
      this.addNewsForm.imageurl = ''
    },
    // 超过图片数量限制
    limit (file) {
      this.$message.error('只能上传一图片')
    },
    // 添加资讯
    SubmitNews () {
      this.$refs.addNewsFormRef.validate(async valid => {
        if (!valid) {
          this.$message.error('请正确填写信息')
        } else {
          const res = await this.$http.post('news/addNews', this.addNewsForm)
          if (res.status !== 200) {
            this.$message.error('发布失败')
          } else {
            this.$message.success('发布成功')
            this.getNewsList()
            this.showAddDialogVisible = false
          }
        }
      })
    }
  }
}
</script>

<style lang="less" scoped>
.news_info {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  .title {
    font-size: 20px;
    margin-bottom: 5px;
  }
  .date {
    margin-bottom: 20px;
  }
  .content {
    font-size: 15px;
    letter-spacing: 1px;
  }
}
.img {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}
.addBtn {
  margin-top: 15px;
}
.dialog-footer {
  margin-right: 30px;
}
.upload-demo {
  width: 50%;
  margin-left: 100px;
}

</style>
